<template>
  <q-form
    @submit="onSubmit"
    @reset="onReset"
    class="q-gutter-md"
  >
    <div class="q-pa-md">
      <div class="q-gutter-md" style="max-width: 300px">
        <p class="text-h4">客户</p>
        <div v-for='item in personInformation'>

          <div v-if='item.propertyType === "dic"'>
            <q-select
              v-model="item.value"
              :options="certificateTypeList"
              :label="item.propertyName"
              @update:model-value='selectType'
            />
          </div>

          <div v-else>
            <q-input v-model=item.value :label=item.propertyName />
          </div>

        </div>

        <p class="text-h4">车辆</p>
        <div v-for='item in carInformation'>
          <q-select
            v-if='item.propertyType=="list0"'
            use-input
            v-model='item.value'
            :label='item.propertyName'
            :options='brandList'
            @update:model-value='selectBrand'
            @filter="filterBrandFn"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  No results
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <div v-else>
            <q-input v-model=item.value :label=item.propertyName />
          </div>

        </div>

        <p class="text-h4">订单</p>
        <div v-for='item in productInformation'>
          <div v-if='item.propertyType == "list10"'>
            <q-input v-model=item.value :label=item.propertyName disable/>
          </div>
          <div v-else-if='item.propertyType == "list11"'>
            <q-select
              v-model="item.value"
              :options="productStoreNameList"
              :label="item.propertyName"
              @update:model-value='selectProductName'
            />
          </div>
          <div v-else-if='item.propertyType == "dic"'>
            <q-select
              v-model="item.value"
              :options="payStyleList"
              :label="item.propertyName"
              @update:model-value='selectPayStyleName'
            />
          </div>
          <div v-else-if='item.propertyType == "image"'>
            <q-uploader
              v-if='item.propertyCode == "otherAccessory"'
              field-name='file'
              :label="item.propertyName"
              multiple
              hide-upload-btn
              auto-upload
              style="max-width: 300px"
              :factory='uploadOtherAccessoryFile'
            />
            <q-uploader
              v-else
              field-name='file'
              :label="item.propertyName"
              multiple
              hide-upload-btn
              auto-upload
              style="max-width: 300px"
              :factory='uploadBillAccessoryFile'
            />
          </div>
          <div v-else>
            <q-input v-model=item.value :label=item.propertyName />
          </div>
        </div>
      </div>
    </div>
    <div>
      <q-btn label="产品树" color="secondary" @click="alert = true" />
      <q-dialog
        v-model="alert"
        full-width
      >
        <q-card style='height: 500px'>
          <q-card-section>
            <TreeEntity
              :reqData='reqData'
              :tickType='mode'
              v-model:tickObj='ticked'
              @update:ticked='tickedFn'
            />
          </q-card-section>

          <q-card-actions align="right" class="bg-white text-teal">
            <q-btn flat label="OK" v-close-popup @click='closeDialog' />
          </q-card-actions>

        </q-card>
      </q-dialog>
    </div>
    <div>
      <q-btn label='报价' type='button' color='primary' @click='quotePrice'/>
      <q-btn label="提交" type="submit" color="primary"/>
      <q-btn label="重置" type="reset" color="primary" flat class="q-ml-sm" />
    </div>
  </q-form>
</template>

<script lang='ts'>
import { api } from 'boot/axios'
import { postRequest, getRequest } from '../../components/functions'
import { useRouter, useRoute } from 'vue-router'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'src/store'
import { ChanReqData } from 'pages/tree/model/Interfaces';
import TreeEntity from '../tree/TreeEntity.vue'

export default {
  name: 'addOrders',
  components: { TreeEntity },
  setup(){
    let alert = ref(false)
    let mode = ref('leaf')
    let reqData = ref<ChanReqData>({
      "entityCode":"301",
      "entityType":"01",
      "length": "999",
      "isRoot":"0",
      "chainHead":"0",
      "entityNo":""
    })
    let router = useRouter();
    let ticked = ref([])
    let rote = useRoute()
    let carInformation = reactive([])
    let productInformation = reactive([])
    let personInformation = reactive([])
    let entityCode = ref(rote.query.entityCode)
    let childCode = ref(rote.query.childCode)
    const store = useStore()
    let operateEvent = ref(rote.query.operateEvent)
    const userData = store.state.sphinx.userData
    let tempBrandList = []
    let brandList = ref(tempBrandList)
    let brandFlag = ref(false)
    let reqBrandData = ref<ChanReqData>({
      "entityCode":"",
      "entityType":"",
      "length": "",
      "isRoot":"",
      "chainHead":"",
      "entityNo":""
    })
    //其它附件上传
    function uploadBillAccessoryFile(file) {
      let reader  = new FileReader();
      reader.addEventListener("load", function () {
          api.post('/file/file/uploadPC',{file:reader.result}).then(res=>{
            productInformation.forEach((item,index,array)=>{
              if(item.propertyCode == "billAccessory"){
                item.value = res.data
              }
            })
            console.log(productInformation);
          })
      }, false);
      if (file) {
        reader.readAsDataURL(file[0]);
      }
    }




    //票据附件上传
    function uploadOtherAccessoryFile(file) {
      let reader  = new FileReader();
      reader.addEventListener("load", function () {
        api.post('/file/file/uploadPC',{file:reader.result}).then(res=>{
          productInformation.forEach((item,index,array)=>{
            if(item.propertyCode == "otherAccessory"){
              item.value = res.data
            }
          })
          console.log(productInformation);
        })
      }, false);
      if (file) {
        reader.readAsDataURL(file[0]);
      }
    }


    //报价
    function quotePrice() {
      let productCode = ''
      productInformation.forEach((item,index,array)=>{
        if(item.propertyCode == "prodectNo"){
          productCode = item.value
        }
      })
      let requestData = {
        "companyId":"9999",
        "channelNo":userData.companyId,
        "productCode":productCode
      }
      postRequest('/transaction/agreement/getAgreement',requestData,res=>{
        let rebateRatio = res.rebateRatio
        let quotePriceData = {
          "codeRelVO" : reqData.value,
          "chains":ticked.value,
          "carTypeId": "",
          "carSeriesId": "4343",
          "addRules": {
            //加价名称
            "commission": {
              //计算方式1、2、3、4 加减乘除
              "clac": "1",
              //计算名称
              "name": "佣金率",
              //计算值
              "value": rebateRatio
            }
          }
        }
        api.post('/transaction/price/caculate',quotePriceData).then((res)=>{
          console.log(res);
          productInformation.forEach((item,index,array)=>{
            if(item.propertyCode == "paidAmt"){
              item.value = res.data.data[0].finalPrice.dataResult
            }
          })
        })
      })

    }
    //获取支付方式对应字典
    let payStyleList = reactive([])
    let payStyleTempList = reactive([])
    function selectFile(val) {
      console.log(val);
    }

    function getPayStyleList(propertyCode) {
      let reqData = {
        entityCode:"303",
        entityType:"01",
        propertyEnglish:propertyCode
      }
      getRequest('/channel/channel/queryEntityPropertyDic',res=>{
        payStyleTempList = res
        res.forEach((item,index,array)=>{
          payStyleList.push(item.dicName)
        })
      },reqData)
    }

    //拿到支付方式的代码，赋值上去
    function selectPayStyleName(val) {
      productInformation.forEach((item,index,array)=>{
        if(item.value == val){
          payStyleTempList.forEach((item0,index,array)=>{
            if(item0.dicName == val){
              item.valueCode = item0.dicCode
            }
          })
        }
      })
    }


    function getPropertyName(entityCode,entityType,sceneCode,objectCodeType) {
      let postData = {
        entityCode: entityCode,
        entityType: entityType,
        sceneCode: sceneCode,
        objectCodeType: objectCodeType,
        companyId: userData.companyId
      };
      postRequest('/channel/channel/instre', postData, (data)=>{
        if(data){
            if(entityCode == "201"){
              data.forEach((item,index,array)=>{
                if(item.propertyType == "list0"){
                  getBrandList(item.propertyCode);
                }
                carInformation.push(
                  {"propertyType":item.propertyType,
                  "propertyCode":item.propertyCode,
                  "propertyName":item.propertyName,
                  "value":''
                  })
              })
            }else if(entityCode == "303"){
              data.forEach((item,index,array)=>{
                if(item.propertyType == "list11"){
                  getProductNameList(item.propertyCode)
                }
                if(item.propertyCode == "payments"){
                  getPayStyleList(item.propertyCode)
                }
                productInformation.push(
                  {
                    "propertyType":item.propertyType,
                    "propertyCode":item.propertyCode,
                    "propertyName":item.propertyName,
                    "value":'',
                    "valueCode": '',
                    "companyId": userData.companyId
                  })
              })
            }else{
              data.forEach((item,index,array)=>{
                personInformation.push(
                  {
                    "propertyType":item.propertyType,
                    "propertyCode":item.propertyCode,
                    "propertyName":item.propertyName,
                    "value":'',
                    "valueCode":'',
                    "companyId": userData.companyId
                  })
              })
            }
        }
      });
    }

    //获取证件类型函数
    let certificateTypeList = ref([])
    let tempCertificateTypeList = ref([])//定义一个存储数据的数组，用来后面找对应的dicNo
    function getCertificateTypeList() {
      const reqData = {
        entityCode:'102',
        entityType:'01',
        propertyEnglish:'identityType'
      }
      getRequest('/channel/channel/queryEntityPropertyDic',res=>{
        tempCertificateTypeList.value = res
        const stringTemp = []
        res.forEach((item,index,array)=>{
          stringTemp.push(item.dicName)
        })
        certificateTypeList.value = stringTemp
      },reqData)
    }
    //选取证件类型函数时，将对应的证件代码(dicNo)赋值进去
    function selectType(val) {
      let dicCode = ''
      tempCertificateTypeList.value.forEach((item,index,array)=>{
        if(item.dicName == val){
          dicCode = item.dicCode
        }
      })
      personInformation.forEach((item,index,array)=>{
        if(item.propertyCode == "identityType"){
          item.valueCode = dicCode
        }
      })
    }

    //获取产品名称列表
    let propertyCodeTemp = ref('')
    let productStoreNameList = reactive([])
    let productTempList = reactive([])
    function getProductNameList(propertyCode) {
      propertyCodeTemp.value = propertyCode

      const reqData = {
        "companyId":userData.companyId,
        "entityCode": entityCode.value,
        "entityType": childCode.value,
        "eventCode": operateEvent.value,
        "propertyCode":propertyCode
      }
      postRequest('channel/channel/getPropertyInterface',reqData,res=>{
        if(res.status == "SUCCESS"){
          let getListUrl = res.data.interfaceEnglish;
          postRequest(getListUrl,{"companyId":userData.companyId},res=>{
            productTempList = res;
            res.forEach((item,index,array)=>{
              productStoreNameList.push(item["seriesName"])
            })
          })
        }
      })
    }


    //选择产品名称获取对应的产品代码
    function selectProductName(val) {
      let seriesNo = ''
      productTempList.forEach((item,index,array)=>{
        if(item.seriesName == val){
          seriesNo = item.seriesNo
        }
      })
      productInformation.forEach((item,index,array)=>{
        if(item.propertyType == "list10"){
          item.value = seriesNo
        }
      })
      reqData.value.entityNo = seriesNo
    }

    //选择树节点时触发的函数
    function tickedFn(tickedId) {
      console.log(tickedId);
    }

    //获取产品树代码
    function getProductCode() {
      let reqCodeData = []
      ticked.value.forEach((item,index,array)=>{
        const {id,chainTail,chainHead,codeName,entityCode,entityType,typeName,entityNo,propertyCodeName} = item.relationNode
        reqCodeData.push({
          "id":id,
          "chainHead":chainHead,
          "entityCode":entityCode,
          "codeName":codeName,
          "entityType":entityType,
          "typeName":typeName,
          "entityNo":entityNo,
          "entityNoName":propertyCodeName,
          "companyId":userData.companyId,
          "companyName":userData.companyName,
          "chainTail":chainTail
        })
      })
      postRequest('/route/route/insertNoTree',reqCodeData,res=>{
        productInformation.forEach((item,index,array)=>{
          if(item.propertyCode == "prodectInstantNo") {
            item.value = res;
          }
        })
      })
    }

    //关闭展示树的框
    function closeDialog() {
      getProductCode()
    }

    function onSubmit() {
      let personData = {}
      let carData = {}
      let productData = {}
      personInformation.forEach((item,index,array)=>{
        if(item.propertyCode == "identityType"){
          personData[item.propertyCode] = item.valueCode
        }else{
          personData[item.propertyCode] = item.value
        }
      })
      carInformation.forEach((item,index,array)=>{
        carData[item.propertyCode] = item.value
      })
      productInformation.forEach((item,index,array)=>{
        if(item.propertyCode == "payments"){
          productData[item.propertyCode] = item.valueCode
        }else{
          productData[item.propertyCode] = item.value
        }
      })
      let orderData = {
        "orderClientVO": personData,
        "orderCarVO": carData,
        "orderPartVO":productData,
        "scene": {
          "chainHead": "",
          "entityNo": "",
          "isRoot": ""
        },
        "companyId": userData.companyId
      }
      postRequest('/transaction/order/addOrder',orderData,res=>{
        console.log(res);
        if(res){
          void router.push('/list?entityCode=' + entityCode.value + '&childCode=' + childCode.value + '&flag=' + 1)
        }
      })
    }
    function onReset() {
      carInformation.forEach((item,index,array)=>{
        item.value = ''
      })
      productInformation.forEach((item,index,array)=>{
        item.value = ''
      })
      personInformation.forEach((item,index,array)=>{
        item.value = ''
      })
    }
    onMounted(()=>{
      let sceneCode = ''
      let requestSceneBody = [
        {
          "entityCode":'101',
          "codeName":'',
          "entityType":'01',
          "typeName":'',
          "eventCode":null,
          "eventName":null,
          "propertyEnglish":null,
          "propertyChinese":null,
          "propertyValue":null,
          "propertyCondition":null,
          "companyId":userData.companyId
        },
        {
          "entityCode":'102',
          "codeName":'',
          "entityType":'02',
          "typeName":'',
          "eventCode":null,
          "eventName":null,
          "propertyEnglish":'roleType',
          "propertyChinese":null,
          "propertyValue":userData.roleType,
          "propertyCondition":null,
          "companyId":userData.companyId
        }];
      api.post('/channel/channel/getSceneCode',requestSceneBody).then(res=>{
        if(res.status == 200){
          sceneCode = res.data.data;
          getPropertyName('201','',sceneCode,'002');//车辆
          getPropertyName('303','01',sceneCode,'002');//订单
          getPropertyName('102','01',sceneCode,'002');//自然人
        }
      })

      // getPropertyName('201','','1010110202202110270000004','002');//车辆
      // getPropertyName('303','01','1010110202202110270000004','002');//订单
      // getPropertyName('102','01','1010110202202110270000004','002');//自然人
      getCertificateTypeList()//拿去证件类型列表
    })
    function selectBrand(val) {
      brandFlag.value = true;
      const entityNo = val.split('.');
      // console.log(entityNo[0]);
      reqBrandData.value = {
        "entityCode":"201",
        "entityType":"00",
        "length": "999",
        "isRoot":"0",
        "chainHead":"0",
        "entityNo":entityNo[0]
      }
    }
    function filterBrandFn(val,update,abort) {
      if (val === '') {
        update(() => {
          brandList.value = tempBrandList
        })
        return
      }

      update(() => {
        const needle = val.toLowerCase()
        brandList.value = tempBrandList.filter(v => v.toLowerCase().indexOf(needle) > -1)
      })
    }
    function getBrandList(propertyCode) {
      let labelName = propertyCode
      console.log('getBrandList_propertyCode',propertyCode);
      const reqData = {
        "companyId":userData.companyId,
        "entityCode": 201,
        "entityType": "",
        "eventCode": operateEvent.value,
        "propertyCode":propertyCode
      }
      postRequest('channel/channel/getPropertyInterface',reqData,res=>{
        if(res.status == "SUCCESS"){
          const tempArray = []
          let getListUrl = res.data.interfaceEnglish;
          getRequest(getListUrl,res=>{
            res.forEach((item,index,array)=>{
              tempArray.push(item[labelName])
              tempBrandList = tempArray
            })
          },{"typeName": ""})
        }
      })
    }
    return {
      onSubmit,
      onReset,
      getPropertyName,
      carInformation,
      productInformation,
      personInformation,
      certificateTypeList,
      entityCode,
      childCode,
      tempCertificateTypeList,
      selectType,
      propertyCodeTemp,
      productStoreNameList,
      productTempList,
      selectProductName,
      alert,
      mode,
      reqData,
      ticked,
      tickedFn,
      closeDialog,
      payStyleList,
      getPayStyleList,
      selectPayStyleName,
      payStyleTempList,
      selectFile,
      quotePrice,
      uploadBillAccessoryFile,
      uploadOtherAccessoryFile,
      selectBrand,
      filterBrandFn,
      brandList
    }
  }
};
</script>

<style scoped>

</style>
